package com.jxb.myshop.dao.impl;

import com.jxb.myshop.dao.UserDao;
import com.jxb.myshop.entity.User;
import com.jxb.myshop.util.DBUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import java.sql.SQLException;

public class UserDaoImpl implements UserDao {
    private QueryRunner qr = new QueryRunner(DBUtil.getDs());
    private String base_select = "select uid,uname,upassword,uemail,usex,ustatus,ucode,urole from user ";

    @Override
    public User getUserByName(String username) throws SQLException {
        return qr.query(base_select + "where uname = ?",
                new BeanHandler<>(User.class),
                username);
    }

    @Override
    public int insertUser(User u) throws SQLException {
        return qr.update("insert into user values(default,?,?,?,?,?,?,?)",
                u.getUname(),
                u.getUpassword(),
                u.getUemail(),
                u.getUsex(),
                u.getUstatus(),
                u.getUcode(),
                u.getUrole());
    }

    @Override
    public User getUserByEmailAndCode(String email, String code) throws SQLException {
        return qr.query(base_select + "where uemail = ? and ucode = ?",
                new BeanHandler<>(User.class),
                email,
                code);
    }

    @Override
    public int changeUserStatus(int uid, int userIsActive) throws SQLException {
        return qr.update("update user set ustatus = ? where uid = ?",
                userIsActive,
                uid);
    }
}
